<template>
  <div class="tip custom-block">
    <p class="font-bold mb-5 text-xl">TIP</p>
    {{ $t('pageLdap.tableRoleGroups.alertContent') }}
  </div>
  <el-row>
    <el-col class="text-right">
      <el-button
        :type="isServiceEnabled ? 'primary' : 'info'"
        round
        class="mr-5"
        :icon="CirclePlus"
        size="large"
        :disabled="!isServiceEnabled"
        @click="ModalAddRoleGroupDialogRef.dialogVisible = true"
      >
        {{ $t('pageLdap.addRoleGroup') }}
      </el-button>
    </el-col>
  </el-row>
  <el-table
    ref="tableRef"
    row-key="groupName"
    :data="TableData"
    style="width: 100%"
  >
    <el-table-column
      prop="groupName"
      :label="$t('pageLdap.tableRoleGroups.groupName')"
      width="180"
    />
    <el-table-column
      prop="groupPrivilege"
      :label="$t('pageLdap.tableRoleGroups.groupPrivilege')"
      width="180"
    />
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button
          class="bg-[var(--el-color-primary)]"
          type="primary"
          size="small"
          @click="handleEdit(scope.row)"
          >{{ $t('global.action.edit') }}</el-button
        >
        <el-button
          size="small"
          type="danger"
          class="bg-orange-600"
          @click="handleDelete(scope.row)"
          >{{ $t('global.action.delete') }}</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <modal-add-role-group
    ref="ModalAddRoleGroupDialogRef"
    :role-group="activeRoleGroup"
    @ok="saveRoleGroup"
  />
</template>

<script setup lang="ts">
import { CirclePlus } from '@element-plus/icons-vue';
import ModalAddRoleGroup from './ModalAddRoleGroup.vue';
import { useLdapStore } from '@/store/UserSecurity/LDAP/LdapStore';
import { useUserManagementStore } from '@/store/UserSecurity/UserManagement/UserManagementStore';
import { useI18n } from 'vue-i18n';

const ldapStore = useLdapStore();
const userManagementStore = useUserManagementStore();
const i18n = useI18n();

const isServiceEnabled = computed(() => ldapStore.isServiceEnabled);
const enabledRoleGroups = computed(() => ldapStore.enabledRoleGroups);
const activeRoleGroup = ref();
const ModalAddRoleGroupDialogRef = ref();
const TableData = computed(() => {
  return enabledRoleGroups.value.map(
    ({
      LocalRole,
      RemoteGroup,
    }: {
      LocalRole: string;
      RemoteGroup: string;
    }) => {
      return {
        groupName: RemoteGroup,
        groupPrivilege: LocalRole,
        actions: [
          {
            value: 'edit',
            title: i18n.t('global.action.edit'),
            enabled: isServiceEnabled.value,
          },
          {
            value: 'delete',
            title: i18n.t('global.action.delete'),
            enabled: isServiceEnabled.value,
          },
        ],
      };
    },
  );
});

onMounted(() => {
  userManagementStore.getAccountRoles();
});

const initRoleGroupModal = (roleGroup: string) => {
  activeRoleGroup.value = roleGroup;
  ModalAddRoleGroupDialogRef.value.dialogVisible = true;
};

const saveRoleGroup = ({
  addNew,
  groupName,
  groupPrivilege,
}: {
  addNew: any;
  groupName: string;
  groupPrivilege: string;
}) => {
  activeRoleGroup.value = null;
  const data = { groupName, groupPrivilege };
  if (addNew) {
    ldapStore
      .addNewRoleGroup(data)
      .then((success: string) =>
        ElNotification({
          type: 'success',
          message: success,
        }),
      )
      .catch(({ message }: { message: string }) =>
        ElNotification({
          type: 'error',
          message,
        }),
      );
  } else {
    ldapStore
      .saveRoleGroup(data)
      .then((success: string) =>
        ElNotification({
          type: 'success',
          message: success,
        }),
      )
      .catch(({ message }: { message: string }) =>
        ElNotification({
          type: 'error',
          message,
        }),
      );
  }
};

const handleEdit = (row: string) => {
  initRoleGroupModal(row);
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    i18n.t('pageLdap.modal.deleteRoleGroupConfirmMessage', {
      groupName: row.groupName,
    }),
    i18n.t('pageLdap.modal.deleteRoleGroup'),
    {
      confirmButtonText: i18n.t('global.action.delete'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      ldapStore
        .deleteRoleGroup({ roleGroups: [row] })
        .then((success: string) =>
          ElNotification({
            type: 'success',
            message: success,
          }),
        )
        .catch(({ message }: { message: string }) =>
          ElNotification({
            type: 'error',
            message,
          }),
        );
    })
    .catch(() => {});
};
</script>
